package com.eudon.ai.agent.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.eudon.ai.agent.common.Constants;


/**
 * @author eudon
 * @description TODO
 * @date 2025/8/7
 * @email syd19970616@gmail.com
 * @address <a href="https://gitee.com/eudon">Gitee</a>
 */
public class Qwen3Http {

    public static void main(String[] args) {
        // API密钥，实际使用时应从环境变量或配置文件中获取
        String apiKey = Constants.API_KEY;

        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "qwen-plus");

        // 构建input对象
        JSONObject input = new JSONObject();
        JSONArray messages = new JSONArray();

        // 添加system消息
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");
        systemMessage.put("content", "You are a helpful assistant.");
        messages.add(systemMessage);

        // 添加user消息
        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", "你是谁？");
        messages.add(userMessage);

        input.put("messages", messages);
        requestBody.put("input", input);

        // 添加parameters
        JSONObject parameters = new JSONObject();
        parameters.put("result_format", "message");
        requestBody.put("parameters", parameters);

        try {
            // 发送HTTP POST请求
            HttpResponse response = HttpRequest.post("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation")
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(JSONUtil.toJsonStr(requestBody))
                    .execute();

            // 处理响应
            if (response.isOk()) {
                String responseBody = response.body();
                System.out.println("响应状态码: " + response.getStatus());
                System.out.println("响应内容: " + responseBody);

                // 解析JSON响应
                JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
                System.out.println("格式化响应: " + JSONUtil.toJsonPrettyStr(jsonResponse));
            } else {
                System.err.println("请求失败，状态码: " + response.getStatus());
                System.err.println("错误信息: " + response.body());
            }

        } catch (Exception e) {
            System.err.println("请求异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 封装的方法，便于复用
     * @param apiKey API密钥
     * @param userContent 用户输入内容
     * @param systemContent 系统提示词（可选）
     * @return 响应结果
     */
    public static String callDashScopeApi(String apiKey, String userContent, String systemContent) {
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "qwen-plus");

        JSONObject input = new JSONObject();
        JSONArray messages = new JSONArray();

        // 如果有系统提示词，添加system消息
        if (systemContent != null && !systemContent.trim().isEmpty()) {
            JSONObject systemMessage = new JSONObject();
            systemMessage.put("role", "system");
            systemMessage.put("content", systemContent);
            messages.add(systemMessage);
        }

        // 添加用户消息
        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", userContent);
        messages.add(userMessage);

        input.put("messages", messages);
        requestBody.put("input", input);

        JSONObject parameters = new JSONObject();
        parameters.put("result_format", "message");
        requestBody.put("parameters", parameters);

        try {
            HttpResponse response = HttpRequest.post("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation")
                    .header("Authorization", "Bearer " + apiKey)
                    .header("Content-Type", "application/json")
                    .body(JSONUtil.toJsonStr(requestBody))
                    .execute();

            if (response.isOk()) {
                return response.body();
            } else {
                throw new RuntimeException("API调用失败，状态码: " + response.getStatus() + ", 错误信息: " + response.body());
            }

        } catch (Exception e) {
            throw new RuntimeException("API调用异常: " + e.getMessage(), e);
        }
    }
}
